package org.csu.mall.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.google.common.collect.Maps;
import org.csu.mall.common.CONSTANT;
import org.csu.mall.common.UniformResponse;
import org.csu.mall.service.IPayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/fastPay/")
public class FastPayController {
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
    @Autowired
    IPayService payService;

    //立即购买
    @PostMapping("fast_pay")
    @ResponseBody
    public UniformResponse fastPay(Integer shippingId, @RequestParam(name="paymentType",defaultValue = "1") Integer paymentType, Integer productId, Integer quantity)
    {
        UniformResponse response=payService.FastPay(shippingId, paymentType, productId, quantity);
        return response;
    }
    //充值余额的支付接口
    @PostMapping("pay_balance")
    @ResponseBody
    public UniformResponse payBalance(BigDecimal balance)
    {
        UniformResponse response=payService.payBalance(balance);
        return  response;
    }
    //回调接口
    @PostMapping("alipay_callback")
    @ResponseBody
    public Object alipayCallback(HttpServletRequest request){
        Map<String ,String> params = Maps.newHashMap();
        Map requestParams = request.getParameterMap();
        for(Iterator iter = requestParams.keySet().iterator(); iter.hasNext();){
            String name = (String)iter.next();
            String[] values = (String[])requestParams.get(name);
            String valueStr = "";
            for(int i = 0 ; i<values.length; i++){
                valueStr = (i == values.length-1)?valueStr + values[i]:valueStr + values[i] + ",";
            }
            params.put(name,valueStr);
        }
        logger.info("支付宝回调,sign:{},trade_status:{},参数:{}",params.get("sign"),params.get("trade_status"),params.toString());

        //非常重要，验证回调的正确性，是不是支付宝的，并且还要避免重复发送
        params.remove("sign_type");
        try {
            boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, Configs.getAlipayPublicKey(),"utf-8",Configs.getSignType());

            if(!alipayRSACheckedV2){
                return UniformResponse.createForErrorMessage("非法请求，验证不通过");
            }
        } catch (AlipayApiException e) {
            logger.error("支付宝回调异常",e);
        }

        //todo 验证各种数据

        UniformResponse response = payService.aliCallback(params);
//        if(response.isSuccess()){
//            session.setAttribute(CONSTANT.TRADESTATUS, response.getData());
////            return UniformResponse.createForSuccess(response);
//        }
        return response;
    }

}
